﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Text;

namespace TestLargeModel.Application
{
    public class TyModel : TyClientBase
    {
        private string _apiKey;
        private string _apiUrl;
        private string _endpointId;
        private static readonly HttpClient client = new HttpClient();

        public TyModel(string configjson) : base(configjson)
        {
            // 解析configjson
            var config = JsonConvert.DeserializeObject<dynamic>(configjson);
            _apiKey = config.ApiKey;
            _apiUrl = config.Url;
            _endpointId = config.EndpointId;
        }

        public override string ChatAI(string input)
        {
            var requestBody = new
            {
                model = _endpointId,
                messages = new[]
                {
                new { role = "system", content = "你是一个编程高手，精通各种编程语言" },
                new { role = "user", content = input }
            },
                stream = true
            };

            var json = JsonConvert.SerializeObject(requestBody);
            var content = new StringContent(json, Encoding.UTF8, "application/json");

            var request = new HttpRequestMessage
            {
                Method = HttpMethod.Post,
                RequestUri = new Uri(_apiUrl),
                Content = content
            };

            request.Headers.Add("Authorization", $"Bearer {_apiKey}");

            var response = client.Send(request, HttpCompletionOption.ResponseHeadersRead);

            var fullResponse = new StringBuilder();

            using (var stream = response.Content.ReadAsStream())
            using (var reader = new System.IO.StreamReader(stream))
            {
                while (!reader.EndOfStream)
                {
                    var line = reader.ReadLine();
                    if (line.StartsWith("data:"))
                    {
                        var jsonString = line.Substring(5).Trim();
                        if (jsonString == "[DONE]")
                        {
                            break;
                        }
                        var jsonObj = JObject.Parse(jsonString);
                        var contentDelta = jsonObj["choices"]?[0]?["delta"]?["content"]?.ToString();
                        if (contentDelta != null)
                        {
                            fullResponse.Append(contentDelta);
                        }
                    }
                }
            }

            return fullResponse.ToString();
        }

        public override IAsyncEnumerable<string> StreamChatAI(string input)
        {
            var requestBody = new
            {
                model = _endpointId,
                messages = new[]
                {
            new { role = "system", content = "你是一个编程高手，精通各种编程语言" },
            new { role = "user", content = input }
        },
                stream = true
            };

            var json = JsonConvert.SerializeObject(requestBody);
            var content = new StringContent(json, Encoding.UTF8, "application/json");

            var request = new HttpRequestMessage
            {
                Method = HttpMethod.Post,
                RequestUri = new Uri(_apiUrl),
                Content = content
            };

            request.Headers.Add("Authorization", $"Bearer {_apiKey}");

            var response = client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead).Result;

            return GetStreamedResponse(response);
        }

        private async IAsyncEnumerable<string> GetStreamedResponse(HttpResponseMessage response)
        {
            using (var stream = await response.Content.ReadAsStreamAsync())
            using (var reader = new System.IO.StreamReader(stream))
            {
                while (!reader.EndOfStream)
                {
                    var line = await reader.ReadLineAsync();
                    if (line.StartsWith("data:"))
                    {
                        var jsonString = line.Substring(5).Trim();
                        if (jsonString == "[DONE]")
                        {
                            yield break;
                        }
                        var jsonObj = JObject.Parse(jsonString);
                        var contentDelta = jsonObj["choices"]?[0]?["delta"]?["content"]?.ToString();
                        if (contentDelta != null)
                        {
                            yield return contentDelta; // 临时返回部分内容
                        }
                    }
                }
            }
        }
    }
}
